package concurrent.juc.readwritelock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author: 黄嘉振
 * @create: 2023/6/15 17:21
 * @description:    普通lock锁读操作不能同时执行；读写锁可以
 **/
public class ReadWriteLockDemo {
    private static Lock lock = new ReentrantLock();
    private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private static Lock read = readWriteLock.readLock();
    private static  Lock write = readWriteLock.writeLock();

    public static void main(String[] args) {
        // 开启读写锁
        boolean openRWLock = false;
        // 启动三个线程 读
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
               if (openRWLock) {
                   execute(read, "开始执行【读】操作");
               } else {
                   execute(lock, "开始执行【读】操作");
               }
            }).start();
        }
        // 启动三个线程 写
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                if (openRWLock) {
                    execute(write, "开始执行【写】操作");
                } else {
                    execute(lock, "开始执行【写】操作");
                }
            }).start();
        }
    }

    public static void execute(Lock lock, String msg) {
        try {
            lock.lock();
            System.out.println(System.currentTimeMillis() / 1000 + " , "
            + Thread.currentThread().getName() + " : " + msg);
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
